import * as API from "./api.js"
import type { UnCancelTokenListener, UnGenericAbortSignal, UnHeaders, post } from '@uni-helper/uni-network'  


/**  
 * 二进制解析成文本  
 * @param data 二进制数据  
 * @returns 文本  
 */  
export function decodeArrayBuffer(data: ArrayBuffer | undefined) {  
  if (!data) {  
    return ''  
  }  
  return decodeUsingURIComponent(data)  
}  

/**  
 * URIComponent解码二进制流(不用引入额外包)  
 * @param data 二进制流  
 * @returns 文本  
 */  
function decodeUsingURIComponent(data: ArrayBuffer) {  
  const uint8Array = new Uint8Array(data)  
  let text = String.fromCharCode(...uint8Array)  
  try {  
    text = decodeURIComponent(escape(text))  
  } catch (e) {  
    console.error('decodeUsingURIComponent: Can not decodeURI ', text)  
  }  
  return text  
}  

type onStreamReceivedListener = (text: string) => void  

export function fetchStreamChat(  
  params: { prompt: string; uuid: string },  
  signal?: UnGenericAbortSignal,  
  listener?: onStreamReceivedListener  
) {  
  const onHeadersReceived = (response?: { headers?: UnHeaders }) => {  
    console.log('fetchStreamChat.onHeadersReceived: ', response?.headers)  
  }  
  const onChunkReceived = (response?: { data?: ArrayBuffer }) => {  
    const text = decodeArrayBuffer(response?.data)  
    console.log("流式返回", text)
    listener?.(text)  
  }  
  return uni.request({  
    url: API.modelChat,  
    headers: {  
      Accept: 'text/event-stream',  
      'Content-Type': 'application/json',  
      // token: 'your-token'  
    }, 
    method: "GET", 
    data: {  
      content: params.prompt,  
      // scene: params.uuid,  
      // source: 'gpt4',  
    },  
    responseType: 'arraybuffer',  
    enableChunked: true,  
    onHeadersReceived,  
    onChunkReceived,  
    signal: signal  
  })  
}